#![allow(unused_imports,dead_code,unused_assignments)]
use axum::{
    extract::{Form, Query, Json, Multipart,DefaultBodyLimit},
    routing::{get,post},
    response::Response,
    body::{Body, Bytes},
    Router
};
use crate::domain::PayTypeBean;
use crate::domain::PayTypeQueryRequest;
use crate::serviceimpl::pay_type_service::activate_all_pay_types as service_activate_all_pay_types;
use crate::serviceimpl::pay_type_service::activate_pay_type as service_activate_pay_type;
use crate::serviceimpl::pay_type_service::add_pay_type as service_add_pay_type;
use crate::serviceimpl::pay_type_service::clone_all_pay_types as service_clone_all_pay_types;
use crate::serviceimpl::pay_type_service::clone_pay_type as service_clone_pay_type;
use crate::serviceimpl::pay_type_service::count_search_pay_types_by_fields_records as service_count_search_pay_types_by_fields_records;
use crate::serviceimpl::pay_type_service::delete_all_pay_types as service_delete_all_pay_types;
use crate::serviceimpl::pay_type_service::delete_pay_type as service_delete_pay_type;
use crate::serviceimpl::pay_type_service::find_pay_type_by_id as service_find_pay_type_by_id;
use crate::serviceimpl::pay_type_service::find_pay_type_by_name as service_find_pay_type_by_name;
use crate::serviceimpl::pay_type_service::list_active_pay_types as service_list_active_pay_types;
use crate::serviceimpl::pay_type_service::list_all_pay_types as service_list_all_pay_types;
use crate::serviceimpl::pay_type_service::search_pay_types_by_fields as service_search_pay_types_by_fields;
use crate::serviceimpl::pay_type_service::search_pay_types_by_fields_by_page as service_search_pay_types_by_fields_by_page;
use crate::serviceimpl::pay_type_service::soft_delete_all_pay_types as service_soft_delete_all_pay_types;
use crate::serviceimpl::pay_type_service::soft_delete_pay_type as service_soft_delete_pay_type;
use crate::serviceimpl::pay_type_service::toggle_one_pay_type as service_toggle_one_pay_type;
use crate::serviceimpl::pay_type_service::toggle_pay_type as service_toggle_pay_type;
use crate::serviceimpl::pay_type_service::update_pay_type as service_update_pay_type;
use crate::utils::excel_util::export_excel_workbook_with_image;
use crate::utils::pdf_util::export_pdf_with_images;
use serde::{Deserialize};
use serde_json::{Value,Map};
use std::fs;
use tower_http::{trace::TraceLayer};


#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PayTypeRequest {
	pub id: Option<i64>,
	pub name: Option<String>,
	pub active: Option<bool>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IdsRequest {
	pub ids: String,
}

pub fn pay_type_controller() -> Router {
	Router::new()
	.route("/listAllPayTypes", post(list_all_pay_types))
	.route("/updatePayType", post(update_pay_type))
	.route("/deletePayType", post(delete_pay_type))
	.route("/addPayType", post(add_pay_type))
	.route("/softDeletePayType", post(soft_delete_pay_type))
	.route("/findPayTypeById", post(find_pay_type_by_id))
	.route("/findPayTypeByName", post(find_pay_type_by_name))
	.route("/listActivePayTypes", post(list_active_pay_types))
	.route("/deleteAllPayTypes", post(delete_all_pay_types))
	.route("/softDeleteAllPayTypes", post(soft_delete_all_pay_types))
	.route("/togglePayType", post(toggle_pay_type))
	.route("/toggleOnePayType", post(toggle_one_pay_type))
	.route("/searchPayTypesByFieldsByPage", post(search_pay_types_by_fields_by_page))
	.route("/activatePayType", post(activate_pay_type))
	.route("/activateAllPayTypes", post(activate_all_pay_types))
	.route("/exportPayTypes", get(export_pay_types))
	.route("/exportPayTypesPDF", get(export_pay_types_pdf))
	.route("/filterPayTypesExcel", get(filter_pay_types_excel))
	.route("/filterPayTypesPDF", get(filter_pay_types_pdf))
	.route("/clonePayType", post(clone_pay_type))
	.route("/cloneAllPayTypes", post(clone_all_pay_types))
	.route("/checkAccessPayType", get(check_access_pay_type))
	.layer(DefaultBodyLimit::max(2*1024*1024))
	.layer(TraceLayer::new_for_http())
}
pub async fn activate_all_pay_types(Form(ids_request):Form<IdsRequest>) ->String {
	let ids = ids_request.ids;
	let string_ids:Vec<&str> = ids.split(',').collect();
	let mut ids:Vec<i64> = Vec::new();

	let vecter_iterator = string_ids.iter();
	for id in vecter_iterator {
		ids.push(id.parse::<i64>().unwrap());
	}

	let _result = service_activate_all_pay_types(ids).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn activate_pay_type(Form(pay_type_request):Form<PayTypeRequest>) ->String {
	let id = pay_type_request.id.unwrap_or_default();
	let _result = service_activate_pay_type(id).await;
	match _result {
		Err(_) => {
			println!("Error!");
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			//println!("{}", resultjson);
			return resultjson;
		}
	}
}

pub async fn add_pay_type(Json(pay_type_request):Json<PayTypeRequest>) ->String {
	let id = pay_type_request.id.unwrap_or_default();
	let name = pay_type_request.name.unwrap_or_default();
	let active = pay_type_request.active.unwrap_or_default();

	let pay_type = PayTypeBean{
	id : id,
	name : name,
	active : active,
	};
	
	let _result = service_add_pay_type(pay_type).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn check_access_pay_type() ->String {
	r#"{  "rows": null,  "success": true}"#.to_string()
}

pub async fn clone_all_pay_types(Form(ids_request):Form<IdsRequest>) ->String {
	let ids = ids_request.ids;
	let string_ids:Vec<&str> = ids.split(',').collect();
	let mut ids:Vec<i64> = Vec::new();

	let vecter_iterator = string_ids.iter();
	for id in vecter_iterator {
		ids.push(id.parse::<i64>().unwrap());
	}

	let _result = service_clone_all_pay_types(ids).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn clone_pay_type(Form(pay_type_request):Form<PayTypeRequest>) ->String {
	let id = pay_type_request.id.unwrap_or_default();
	let _result = service_clone_pay_type(id).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn delete_all_pay_types(Form(ids_request):Form<IdsRequest>) ->String {
	let ids = ids_request.ids;
	let string_ids:Vec<&str> = ids.split(',').collect();
	let mut ids:Vec<i64> = Vec::new();

	let vecter_iterator = string_ids.iter();
	for id in vecter_iterator {
		ids.push(id.parse::<i64>().unwrap());
	}

	let _result = service_delete_all_pay_types(ids).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn delete_pay_type(Form(pay_type_request):Form<PayTypeRequest>) ->String {
	let id = pay_type_request.id.unwrap_or_default();
	let _result = service_delete_pay_type(id).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn export_pay_types() ->Response<Body> {
	let list = service_list_all_pay_types().await.unwrap();
	let mut contents : Vec<Vec<String>> = Vec::new();
	let sheet_name = "支付方式信息表".to_string();
	let headers = vec!["序号".to_string(),"名字".to_string(),"活跃".to_string()];
	let is_images = vec![false,false,false];
	for pay_type in list {

		let row = vec![pay_type.id.to_string(),pay_type.name,pay_type.active.to_string()];
		contents.push(row);
	}

	let full_file_path = "./template/temp/payTypes.xlsx";
	export_excel_workbook_with_image(full_file_path.to_string(),sheet_name, headers, contents, is_images);
	
	
	let data = fs::read(full_file_path).unwrap();
	let _ = fs::remove_file(full_file_path);

	Response::builder()
	.header("Content-Type", "application/octet-stream")
	.header("Content-Disposition", "attachment; filename=payTypes.xlsx")
	.header("Content-Transfer-Encoding", "binary")
	.body(Body::from(data))
	.unwrap()
}

pub async fn export_pay_types_pdf() ->Response<Body> {
	let list = service_list_all_pay_types().await.unwrap();
	let mut contents : Vec<Vec<String>> = Vec::new();
	let sheet_name = "支付方式信息表".to_string();
	let headers = vec!["序号".to_string(),"名字".to_string(),"活跃".to_string()];
	let is_images = vec![false,false,false];
	for pay_type in list {

		let row = vec![pay_type.id.to_string(),pay_type.name,pay_type.active.to_string()];
		contents.push(row);
	}

	let data = export_pdf_with_images(sheet_name, headers, contents, is_images);
	
	Response::builder()
	.header("Content-Type", "application/octet-stream")
	.header("Content-Disposition", "attachment; filename=payTypes.pdf")
	.header("Content-Transfer-Encoding", "binary")
	.body(Body::from(data))
	.unwrap()
}

pub async fn filter_pay_types_excel(Query(pay_type_query_request):Query<PayTypeQueryRequest>) ->Response<Body> {
	let list = service_search_pay_types_by_fields(pay_type_query_request).await.unwrap();
	let mut contents : Vec<Vec<String>> = Vec::new();
	let sheet_name = "支付方式信息表".to_string();
	let headers = vec!["序号".to_string(),"名字".to_string(),"活跃".to_string()];
	let is_images = vec![false,false,false];
	for pay_type in list {

		let row = vec![pay_type.id.to_string(),pay_type.name,pay_type.active.to_string()];
		contents.push(row);
	}

	let full_file_path = "./template/temp/payTypes.xlsx";
	export_excel_workbook_with_image(full_file_path.to_string(),sheet_name, headers, contents, is_images);
	
	
	let data = fs::read(full_file_path).unwrap();
	let _ = fs::remove_file(full_file_path);

	Response::builder()
	.header("Content-Type", "application/octet-stream")
	.header("Content-Disposition", "attachment; filename=payTypes.xlsx")
	.header("Content-Transfer-Encoding", "binary")
	.body(Body::from(data))
	.unwrap()
}

pub async fn filter_pay_types_pdf(Query(pay_type_query_request):Query<PayTypeQueryRequest>) ->Response<Body> {
	let list = service_search_pay_types_by_fields(pay_type_query_request).await.unwrap();
	let mut contents : Vec<Vec<String>> = Vec::new();
	let sheet_name = "支付方式信息表".to_string();
	let headers = vec!["序号".to_string(),"名字".to_string(),"活跃".to_string()];
	let is_images = vec![false,false,false];
	for pay_type in list {

		let row = vec![pay_type.id.to_string(),pay_type.name,pay_type.active.to_string()];
		contents.push(row);
	}

	let data = export_pdf_with_images(sheet_name, headers, contents, is_images);

	Response::builder()
	.header("Content-Type", "application/octet-stream")
	.header("Content-Disposition", "attachment; filename=payTypes.pdf")
	.header("Content-Transfer-Encoding", "binary")
	.body(Body::from(data))
	.unwrap()
}

pub async fn find_pay_type_by_id(Form(pay_type_request):Form<PayTypeRequest>) ->String {
	let id = pay_type_request.id.unwrap_or_default();
	let pay_type = service_find_pay_type_by_id(id).await;
	match pay_type {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(pay_type) => {
			let json = serde_json::to_string_pretty(&pay_type).unwrap();

			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				serde_json::from_str(&json).unwrap(),
			);
		
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn find_pay_type_by_name(Form(pay_type_request):Form<PayTypeRequest>) ->String {
	let name = pay_type_request.name.unwrap_or_default();
	let pay_type = service_find_pay_type_by_name(name).await;
	match pay_type {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(pay_type) => {
			let json = serde_json::to_string_pretty(&pay_type).unwrap();

			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				serde_json::from_str(&json).unwrap(),
			);
		
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn list_active_pay_types() ->String {
	let pay_types = service_list_active_pay_types().await;
	match pay_types {
		Err(_) => {
			println!("Error!");
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(pay_types) => {
			let json = serde_json::to_string_pretty(&pay_types).unwrap();
			//println!("{}", json);

			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				serde_json::from_str(&json).unwrap(),
			);
		
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			//println!("{}", resultjson);
			return resultjson;
		}
	}
}

pub async fn list_all_pay_types() ->String {
	let pay_types = service_list_all_pay_types().await;
	match pay_types {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(pay_types) => {
			let json = serde_json::to_string_pretty(&pay_types).unwrap();

			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				serde_json::from_str(&json).unwrap(),
			);
		
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn search_pay_types_by_fields_by_page(Form(pay_type_query_request):Form<PayTypeQueryRequest>) ->String {
	let pay_types = service_search_pay_types_by_fields_by_page(pay_type_query_request.clone()).await;
	let total = service_count_search_pay_types_by_fields_records(pay_type_query_request.clone()).await.unwrap().count_num;
	match pay_types {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(pay_types) => {
			let json = serde_json::to_string_pretty(&pay_types).unwrap();

			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert("total".to_string(), Value::from(total));
			map.insert(
				"rows".to_string(),
				serde_json::from_str(&json).unwrap(),
			);
		
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn soft_delete_all_pay_types(Form(ids_request):Form<IdsRequest>) ->String {
	let ids = ids_request.ids;
	let string_ids:Vec<&str> = ids.split(',').collect();
	let mut ids:Vec<i64> = Vec::new();

	let vecter_iterator = string_ids.iter();
	for id in vecter_iterator {
		ids.push(id.parse::<i64>().unwrap());
	}

	let _result = service_soft_delete_all_pay_types(ids).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn soft_delete_pay_type(Form(pay_type_request):Form<PayTypeRequest>) ->String {
	let id = pay_type_request.id.unwrap_or_default();
	let _result = service_soft_delete_pay_type(id).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn toggle_one_pay_type(Form(pay_type_request):Form<PayTypeRequest>) ->String {
	let id = pay_type_request.id.unwrap_or_default();
	let _result = service_toggle_one_pay_type(id).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn toggle_pay_type(Form(pay_type_request):Form<PayTypeRequest>) ->String {
	let id = pay_type_request.id.unwrap_or_default();
	let _result = service_toggle_pay_type(id).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn update_pay_type(Json(pay_type_request):Json<PayTypeRequest>) ->String {
	let id = pay_type_request.id.unwrap_or_default();
	let name = pay_type_request.name.unwrap_or_default();
	let active = pay_type_request.active.unwrap_or_default();
	let _current_pay_type = service_find_pay_type_by_id(id).await.unwrap();

	let pay_type = PayTypeBean{
	id : id,
	name : name,
	active : active,
	};
	
	let _result = service_update_pay_type(pay_type).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

